package com.example.dzcfinal;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class InputActivity extends Activity {
    SQLiteDatabase db;
    Button bn = null;
    ListView listView;
    EditText titles;
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_input);
        //给数据库变量赋值，值为绝对路径file下的sqLite数据库，如果不存在，则创建一个数据库，命名为my.db3
        db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString() + "/my.input" , null);
        listView = (ListView)findViewById(R.id.show);
        titles = (EditText) findViewById(R.id.title);
        bn = (Button)findViewById(R.id.ok);

        bn.setOnClickListener(new View.OnClickListener(){
            @Override
            //设置按钮的匿名内部类点击
            public void onClick(View source){
                String title = titles.getText().toString();
                try {
                    insertData(db , title);
                    //插入数据后进行查询语句，目的是更新视图，将查询到的数据存放在cursor对象中
                    Cursor cursor = db.rawQuery("select * from news_inff", null);
                    inflateList(cursor);
                    titles.setText("");

                }catch(SQLiteException se){
                    db.execSQL("create	table	news_inff(_id	integer	primary	key autoincrement,"	+ "news_title varchar(255)"+")");
                    insertData(db , title);
                    //插入数据后进行查询语句，目的是更新视图，将查询到的数据存放在cursor对象中
                    Cursor cursor = db.rawQuery("select * from news_inff", null);
                    inflateList(cursor);
                    titles.setText("");
                }
            }
        });
    }
    private void insertData(SQLiteDatabase db, String title ){
        db.execSQL("insert into news_inff values(null , ?)", new String[]{title});
    }
    private void inflateList(Cursor cursor){
        //给cursor对象添加adapter适配器
        SimpleCursorAdapter adapter= new SimpleCursorAdapter( InputActivity.this , R.layout.layout_line, cursor
                , new String[]{"news_title"}
                , new int[]{R.id.my_title});
        //给列表控件设置适配器
        listView.setAdapter(adapter);
    }
    //继承销毁方法
    @Override
    public void onDestroy(){
        super.onDestroy();
        //当数据库不为空或者数据库为打开状态时，关闭数据库
        if (db != null && db.isOpen()){
            db.close();
        }
    }
}
